package com.share.security;


import cn.hutool.json.JSONUtil;

import com.share.domain.*;

import com.share.service.SysMenuService;
import com.share.service.SysRoleService;
import com.share.service.SysUserService;
import com.share.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 登录成功处理器
 * @author java1234_小锋 （公众号：java1234）
 * @site www.java1234.vip
 * @company 南通小锋网络科技有限公司
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String username=authentication.getName();
        String token = JwtUtils.genJwtToken(username);

//        SysUser currentUser = sysUserService.getByUsername(username);
//        if (currentUser==null){
//           throw  new UserCountLockException("当前用户不存在");
//        }
//        //根据用户id获取所有的角色信息
//        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id =" + currentUser.getId()));
//
//        Set<Long> menuSet = new HashSet<>();
//        //遍历所有的角色，获取所有的菜单权限，而且不重复
//        List<SysMenu> menuList = new ArrayList<>();
//        for (SysRole sysRole : roleList) {
//            List<SysMenu> sysMenuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "select menu_id from sys_role_menu where role_id = " + sysRole.getId()));
//            for (SysMenu sysMenu : sysMenuList) {
//                  if (!menuSet.contains(sysMenu.getId())){
//                      menuList.add(sysMenu);
//                      menuSet.add(sysMenu.getId());
//                  }
//            }
//        }
//
//        //排序
//        menuList.sort(Comparator.comparing(SysMenu::getOrdernum));
//        //转菜单树
//        List<SysMenu> menuList1 = sysMenuService.buildTreeMenu(menuList);
//
        httpServletResponse.setHeader("authorization",token);
        Result result = Result.succ("");
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();
    }
}
